<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8" >
            <a-form-model-item label="成本价方案" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.name" :length="16"></j-ellipsis>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="物流渠道" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.channelName" :length="16"></j-ellipsis>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="计算方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-ellipsis :value="model.calculateMethod_dictText" :length="16"></j-ellipsis>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="报价版本" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="version">
              <a-input placeholder="请输入报价版本" v-model="model.version" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <!-- 从历史版本进入编辑页面不允许编辑生效时间 -->
            <a-form-model-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol" v-if="pageType === 'historyQuotation'">
              <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" disabled />
            </a-form-model-item>
            <a-form-model-item label="生效时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="effectBeginTime" v-else>
              <j-date placeholder="请选择生效时间"  v-model="model.effectBeginTime" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" :disabled-date="disabledDate" :disabled-time="disabledTime" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="创建类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio" v-model="model.sourceType" dictCode="logistics_cost_price_source_type" placeholder="请选择创建类型" @change="sourceTypeChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-if="model.sourceType === 'config'">
          <a-col :span="8" >
            <a-form-model-item label="分区方案" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag ref="partitionIdRef" v-model="model.partitionId" :disabled="!model.channelId" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" >
            <a-form-model-item label="重量段方案" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag ref="weightRangeIdRef" v-model="model.weightRangeId" dict="hz_logistics_weight_range,name,id,logistics,able_status='2'" :disabled="!model.channelId" />
            </a-form-model-item>
          </a-col>
          <a-button type="primary" style="margin: 4px 0 0 20px;" @click="handleCreate" :disabled="!(model.partitionId && model.weightRangeId)">创建组合</a-button>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            class="j-table-force-nowrap"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            >
            <span slot="action" slot-scope="text, record">
              <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record)">
                <a>删除</a>
              </a-popconfirm>
            </span>
          </a-table>
        </a-row>
        <div class="table-operator" v-if="!formDisabled">
          <a-button type="primary" icon="download" @click="handleExportXls_('物流成本价维护详情',url.logisticsCostPriceDetail.exportExcelUrl,exportParams)" :disabled="!(logisticsCostPriceDetailTable.dataSource && logisticsCostPriceDetailTable.dataSource.length)">成本价导出</a-button>
          <template v-if="model.sourceType === 'config'">
            <a-upload name="file" :data="exportParams_" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportDetailExcel">
              <a-button type="primary" icon="import">成本价导入</a-button>
            </a-upload>
            <a-button type="primary" @click="handleBatchCost">批量费用</a-button>
          </template>
          <template v-if="model.sourceType === 'import'">
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="analysisExcel" @change="handleImportDetailExcel">
              <a-button type="primary" icon="import">成本价导入</a-button>
            </a-upload>
            <a-button type="primary" @click="handleExportXls('物流成本价模板',url.logisticsCostPriceDetail.downloadTemplate)">下载模板</a-button>
          </template>
        </div>
        <j-editable-table
          :ref="refKeys[0]"
          :loading="logisticsCostPriceDetailTable.loading"
          :columns="logisticsCostPriceDetailTable.columns"
          :dataSource="logisticsCostPriceDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          @valueChange="handleValueChange"
        />
      </a-form-model>
    </j-form-container>
    <logistics-cost-price-form-modal ref="modalForm" @ok="modalFormOk"></logistics-cost-price-form-modal>
  </a-spin>
</template>

<script>
  import { getAction, downFile_, deleteAction } from '@/api/manage'
  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import Vue from 'vue'
  import { ACCESS_TOKEN } from "@/store/mutation-types"
  import moment from 'moment'
  import LogisticsCostPriceFormModal from './LogisticsCostPriceFormModal' 

  export default {
    name: 'LogisticsChangeQuotationForm',
    mixins: [JEditableTableModelMixin,JeecgListMixin],
    components: { LogisticsCostPriceFormModal },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          sourceType: 'config',
        },
        exportParams:{},
        exportParams_: {},
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          channelId: [
            { required: true, message: '请选择所属物流渠道!'},
          ],
          providerId: [
            { required: true, message: '请输入物流商!'},
          ],
          calculateMethod: [
            { required: true, message: '请输入计算方式!'},
          ],
          // weightRangeId: [
          //   { required: true, message: '请输入重量段方案!'},
          // ],
          // partitionId: [
          //   { required: true, message: '请输入分区方案!'},
          // ],
          // effectTime: [
          //   { required: true, message: '请输入生效时间!'},
          //   { validator: this.validEffectTime}
          // ],
          name: [
            { required: true, message: '请输入成本价方案名称!' }
          ],
          version: [
            { required: true, message: '请输入报价版本!' }
          ],
          effectBeginTime: [
            { required: true, message: '请选择生效时间!' },
            { validator: this.validEffectBeginTime }
          ]
        },
        disableMixinCreated: true,
        refKeys: ['logisticsCostPriceDetail', ],
        tableKeys:['logisticsCostPriceDetail', ],
        activeKey: 'logisticsCostPriceDetail',
        // 物流成本价详情
        logisticsCostPriceDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '收费分区',
              key: 'classifyId',
              type: FormTypes.select,
              width:"115px",
              dictCode:"hz_logistics_partition_classify,name,id,logistics",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '计费类型',
              key: 'chargeType',
              type: FormTypes.select,
              dictCode:"logistics_charge_type",
              width:"115px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '开始重量段（KG）',
              key: 'startWeight',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '结束重量段（KG）',
              key: 'endWeight',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '最低计费重（KG）',
              key: 'minChargeWeight',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '',
              defaultValue:'',
              disabled: true
            },
            {
              title: '计费单重（KG）',
              key: 'chargeWeight',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true
            },
            {
              title: '价格值',
              key: 'price',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
              validateRules: [{ required: true, message: '${title}不能为空' }],
            },
            {
              title: '挂号费',
              key: 'registerFee',
              type: FormTypes.inputNumber,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/logistics/costPrice/logisticsCostPrice/add",
          edit: "/logistics/costPrice/logisticsCostPrice/changePrice",
          queryById: "/logistics/costPrice/logisticsCostPrice/queryById",
          logisticsCostPriceDetail: {
            list: '/logistics/costPrice/logisticsCostPrice/queryHzLogisticsCostPriceDetailByMainId',
            queryInitDetail: '/logistics/costPrice/logisticsCostPrice/queryInitDetail',
            exportExcelUrl: '/logistics/costPrice/logisticsCostPrice/detail/exportExcel',
            importExcelUrl: 'logistics/costPrice/logisticsCostPrice/detail/importExcel',
            analysisExcel: 'logistics/costPrice/logisticsCostPrice/detail/analysisExcel',
            queryCompose: '/logistics/costPrice/logisticsCostPrice/queryCompose',
            allByParam: '/logistics/part/logisticsPartition/allByParam',
            queryLatestVersion: '/logistics/costPrice/logisticsCostPrice/queryLatestVersion',
            downloadTemplate: '/logistics/costPrice/logisticsCostPrice/downloadTemplate',
            queryVersionList: '/logistics/costPrice/logisticsCostPrice/queryVersionList',
            delete: "/logistics/costPrice/logisticsCostPrice/delete",
          },
        },
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'分区方案',
            align:"center",
            dataIndex: 'partitionId_dictText'
          },
          {
            title:'重量段方案',
            align:"center",
            dataIndex: 'weightId_dictText'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        dataSource: [],
        logisticsCostPriceDetailTableDataSource: [],
        lastTime: moment(),
        configDataSource: [],
        importDataSource: [],
        dictOptions: [],
        pageType: ''
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.logisticsCostPriceDetail.importExcelUrl}`;
      },
      analysisExcel: function(){
        return `${window._CONFIG['domianURL']}/${this.url.logisticsCostPriceDetail.analysisExcel}`;
      }
    },
    watch: {
      dataSource: {
        handler(){
          this.model.logisticsCostPriceComposeList = this.dataSource.map(item => {
            return {
              partitionId: item.partitionId,
              weightId: item.weightId
            }
          })
          //导出数据、上传数据入参需要创建分区重量组合数据
          let dataSource = this.dataSource.map(item => {
            return {
              partitionId: item.partitionId,
              weightRangeId: item.weightId
            }
          });
          this.exportParams = {
            id: this.model.id || '',
            partitionWeightList: [...dataSource]
          }
          this.exportParams_ = {
            id: this.model.id || '',
            partitionWeightList: JSON.stringify([...dataSource])
          }
        }
      },
    },
    methods: {
      addBefore(){
        this.logisticsCostPriceDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        if(!this.model.sourceType){
          this.$set(this.model, 'sourceType', 'config');
        }
        this.exportParams["id"] = this.model.id || '';
        this.exportParams_["id"] = this.model.id || '';

        // 加载子表数据
        if (this.model.id) {
          //获取最新版本详情
          this.getQueryLatestVersion();
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.logisticsCostPriceDetail.list, params, this.logisticsCostPriceDetailTable, (res) => {
            this.logisticsCostPriceDetailTableDataSource = res.result;
          })
          // 系统配置table数据
          this.getQueryCompose();
          // 分区方案数据源
          this.channelIdChange();
        }
      },
      initDetail() {
        //初始化成本价详情数据
        if(this.model.partitionId && this.model.weightRangeId){
          let params = {
            partitionId: this.model.partitionId ,
            weightRangeId: this.model.weightRangeId
          };
          this.requestSubTableData(this.url.logisticsCostPriceDetail.queryInitDetail, params, this.logisticsCostPriceDetailTable, (res) => {
            this.logisticsCostPriceDetailTableDataSource = [...this.logisticsCostPriceDetailTableDataSource, ...(res.result || [])];
            this.logisticsCostPriceDetailTable.dataSource = [...this.logisticsCostPriceDetailTableDataSource];
          })

        }
      },
      /* 导入 */
      handleImportDetailExcel(info){
        this.loading = true;
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          this.loading = false;
          if (info.file.response.success) {
            // this.$message.success(`${info.file.name} 文件上传成功`);
            if (info.file.response.code === 201) {
              let { message, result: { msg, fileUrl, fileName } } = info.file.response
              this.$warning({
                title: message,
                content: (<div>
                    <span>{msg}</span><br/>
                    <span>具体详情请 <a href={fileUrl} target="_blank" download={fileName}>点击下载</a> </span>
                  </div>
                )
              })
            } else {
              this.logisticsCostPriceDetailTable.dataSource=info.file.response.result.dataList;
              this.logisticsCostPriceDetailTableDataSource = info.file.response.result.dataList;
              this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`);
              console.log("uploadData"+JSON.stringify(info.file.response));
            }
            //this.loadData()
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.loading = false;
          if (info.file.response.status === 500) {
            let data = info.file.response
            const token = Vue.ls.get(ACCESS_TOKEN)
            if (token && data.message.includes("Token失效")) {
              this.$error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                  store.dispatch('Logout').then(() => {
                    Vue.ls.remove(ACCESS_TOKEN)
                    window.location.reload();
                  })
                }
              })
            }else{
              this.$message.error(`文件上传失败: ${info.file.response.message} `);
            }
          } else {
            this.$message.error(`文件上传失败: ${info.file.msg} `);
          }
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
          return new Promise((resolve,reject)=>{
            Promise.all([
            ]).then(() => {
              resolve(allValues)
            }).catch(e => {
              if (e.error === VALIDATE_NO_PASSED) {
                // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
              } else {
                console.error(e)
              }
            })
          })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          logisticsCostPriceDetailList: this.logisticsCostPriceDetailTableDataSource,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      validEffectBeginTime(rule, value, callback){
        if(!value){
          callback('请选择生效时间!');
        }else{
          if(moment(moment(value).format('YYYY-MM-DD HH:mm:ss')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm:ss')))){
            callback('生效时间需晚于最新版本时间或系统时间!');
          }else{
            callback();
          }
        }
      },
      handleCreate(){
        //重复判断
        let flag = this.dataSource.some(item => {
          return item.partitionId === this.model.partitionId;
        })
        if(flag){
          this.$message.warning('分区方案已存在!');
          return;
        }
        let dictOptions = this.$refs.partitionIdRef && this.$refs.partitionIdRef.getCurrentDictOptions();
        let weightDictOptions = this.$refs.weightRangeIdRef && this.$refs.weightRangeIdRef.getCurrentDictOptions();
        let result = dictOptions && dictOptions.find(item => item.value === this.model.partitionId);
        let weightResult = weightDictOptions && weightDictOptions.find(item => item.value === this.model.weightRangeId);
        this.dataSource.push({
          id: +this.dataSource.length+1,
          partitionId: result.value,
          partitionId_dictText: result.text,
          weightId: weightResult.value,
          weightId_dictText: weightResult.text
        })
        this.initDetail();
      },
      handleDelete(record){
        let dataSource = this.dataSource.filter(item => item.id != record.id);
        this.dataSource = dataSource.map((item, index) => {
          return {
            ...item,
            id: +index+1
          }
        })
        if(!(this.logisticsCostPriceDetailTableDataSource && this.logisticsCostPriceDetailTableDataSource.length)){
          this.logisticsCostPriceDetailTableDataSource = [...this.logisticsCostPriceDetailTable.dataSource];
        }
        this.logisticsCostPriceDetailTableDataSource = this.logisticsCostPriceDetailTableDataSource.filter(item => {
          return !(item.partitionId === record.partitionId && item.weightRangeId === record.weightId)
        });
        this.logisticsCostPriceDetailTable.dataSource = [...this.logisticsCostPriceDetailTableDataSource];
      },
      getQueryCompose(){
        getAction(this.url.logisticsCostPriceDetail.queryCompose, {id: this.model.id}).then((res) => {
          if(res.success){
            this.dataSource = res.result;
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleOk_(){
        if(this.model.sourceType === 'config'){
          if(!(this.dataSource && this.dataSource.length)){
            this.$message.warning('请创建分区重量组合表!');
            return;
          }
          delete this.model.partitionId;
          delete this.model.weightRangeId;
        }else{
          //文件导入，创建分区重量组合数据
          delete this.model.partitionId;
          delete this.model.weightRangeId;
          this.model.logisticsCostPriceComposeList = [];
        }
        if(!(this.logisticsCostPriceDetailTable.dataSource && this.logisticsCostPriceDetailTable.dataSource.length)){
          this.$message.warning('请创建分区重量表!');
          return;
        }
        // 历史报价中的编辑要接口改为
        if(this.pageType === 'historyQuotation'){
          this.url.edit = '/logistics/costPrice/logisticsCostPrice/edit';
        }
        this.handleOk();
      },
      handleValueChange({ row }){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          let tables = this.$refs[ref].getValuesSync();
          tables = tables.values;
          let index = tables.findIndex(item => item.id === row.id);
          this.logisticsCostPriceDetailTableDataSource.splice(index, 1, {
            ...this.logisticsCostPriceDetailTableDataSource[index],
            ...row
          });
        }
      },
      channelIdChange(){
        //清空数据
        this.$set(this.model, 'partitionId', '');
        this.$set(this.model, 'weightRangeId', '');
        this.dataSource = [];
        this.logisticsCostPriceDetailTable.dataSource = [];
        this.logisticsCostPriceDetailTableDataSource = [];
        this.$refs.partitionIdRef && this.$refs.partitionIdRef.setCurrentDictOptions([]);
        let params = {
          isEnable: 'Y',
          channelId: this.model.channelId
        }
        getAction(this.url.logisticsCostPriceDetail.allByParam, params).then((res) => {
          if(res.success){
            this.dictOptions = res.result && res.result.map(item => {
              return {
                value: item.id,
                text: item.name
              }
            });
            this.$refs.partitionIdRef && this.$refs.partitionIdRef.setCurrentDictOptions(this.dictOptions);
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      //fileName 文件名，templateUrl 模板路径，params 单条导出数据入参，callback 回调
      handleExportXls_(fileName, templateUrl, params, callback){
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        let param = this.getQueryParams();
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        param = params || param;
        console.log("导出参数",param)
        let exportXlsUrl;
        if(templateUrl === 'template'){
          exportXlsUrl = this.url.exportTemplateXlsUrl;
        }else if(templateUrl && templateUrl != 'template'){
          exportXlsUrl = templateUrl;
        }else{
          exportXlsUrl = this.url.exportXlsUrl;
        }
        downFile_(exportXlsUrl,param).then((data)=>{
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (data.type === 'application/json') {
            this.blobToJson(data).then((res) => {
              this.$message.warning(res.message)
            })
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xlsx')
          }else{
            let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            if (exportXlsUrl.indexOf("/flowable/") !== -1){
              link.setAttribute('download', fileName+'.xls')
            }else {
              link.setAttribute('download', fileName+'.xlsx')
            }
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        }).finally(() => {
          callback && callback();
        })
      },
      getQueryLatestVersion(){
        getAction(this.url.logisticsCostPriceDetail.queryLatestVersion, { code: this.model.code }).then((res) => {
          if(res.success){
            let lastTime = res.result && res.result.effectBeginTime;
            // 如果最新版本晚于当前时间，则取最新版版本(下一秒)为校验时间
            if(moment(moment(lastTime).format('YYYY-MM-DD HH:mm:ss')).isAfter(moment(moment().format('YYYY-MM-DD HH:mm:ss')))){
              lastTime = moment(lastTime).add(1, 'seconds');
              this.lastTime = lastTime;
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      disabledDate(current){
        // 禁用今天之前的日期
        return current && current < moment(this.lastTime).subtract(1, 'days').endOf('day');
      },
      disabledTime(current){
        let hourList = Array.from({ length: 24 }, (_, index) => index);
        let minutesList = Array.from({ length: 60 }, (_, index) => index);
        let secondsList = Array.from({ length: 60 }, (_, index) => index);
        // 1.选择时间晚于当前(天)
        if(moment(moment(current).format('YYYY-MM-DD')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          return {
            disabledHours: () => [],
            disabledMinutes: () => [],
            disabledSeconds: () => [],
          };
        }else if(moment(moment(current).format('YYYY-MM-DD')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD')))){
          //3.编辑返参早于当前
          return {
            disabledHours: () => hourList,
            disabledMinutes: () => minutesList,
            disabledSeconds: () => secondsList,
          };
        }
        // 2.选择时间等于当前(天)
        let currentHourList = [], currentminutesList = [], currentsecondsList = [];
        if(moment(current).format('YYYY-MM-DD') === moment(this.lastTime).format('YYYY-MM-DD')){
          // 选择的时间为限制时间之后
          currentHourList = hourList.filter(item => item < moment(this.lastTime).format('HH'));
          // 2.选择时间等于当前(时)
          if(moment(current).format('YYYY-MM-DD HH') === moment(this.lastTime).format('YYYY-MM-DD HH')){
            // 选择的时间为限制时间之后
            currentminutesList = minutesList.filter(item => item < moment(this.lastTime).format('mm'));
            // 2.选择时间等于当前(分)
            if(moment(current).format('YYYY-MM-DD HH:mm') === moment(this.lastTime).format('YYYY-MM-DD HH:mm')){
              currentsecondsList = secondsList.filter(item => item < moment(this.lastTime).format('ss'));
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间晚于当前(分)
              currentsecondsList = [];
            }else if(moment(moment(current).format('YYYY-MM-DD HH:mm')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH:mm')))){
              // 选择时间早于当前(分)
              currentsecondsList = secondsList;
            }
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isAfter(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间晚于当前(时)
            currentminutesList = [];
            currentsecondsList = [];
          }else if(moment(moment(current).format('YYYY-MM-DD HH')).isBefore(moment(moment(this.lastTime).format('YYYY-MM-DD HH')))){
            // 选择时间早于当前(时)
            currentminutesList = minutesList;
            currentsecondsList = secondsList;
          }
          return {
            disabledHours: () => currentHourList,
            disabledMinutes: () => currentminutesList,
            disabledSeconds: () => currentsecondsList,
          };
        }
      },
      sourceTypeChange(){
        // 创建类型切换，保存自有的分区重量表数据，给当前创建类型的分区重量表赋值
        if(this.model.sourceType === 'import'){
          this.configDataSource = this.logisticsCostPriceDetailTableDataSource;
          this.logisticsCostPriceDetailTableDataSource = this.importDataSource;
          this.logisticsCostPriceDetailTable.dataSource = this.importDataSource;
        }else if(this.model.sourceType === 'config'){
          this.importDataSource = this.logisticsCostPriceDetailTableDataSource;
          this.logisticsCostPriceDetailTableDataSource = this.configDataSource;
          this.logisticsCostPriceDetailTable.dataSource = this.configDataSource;
          //分区方案数据源
          this.$nextTick(() => {
            this.$refs.partitionIdRef && this.$refs.partitionIdRef.setCurrentDictOptions(this.dictOptions);
          })
        }
      },
      handleBatchCost(){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          let currentSelection = this.$refs[ref].getSelection();
          if(!currentSelection.length){
            this.$message.warning('请选择数据!');
            return;
          }
          this.$refs.modalForm.add();
          this.$refs.modalForm.title = "批量费用设置";
          this.$refs.modalForm.disableSubmit = false;
        }
      },
      modalFormOk(model){
        let ref = this.refKeys[0];
        if(this.$refs[ref]){
          let currentSelection = this.$refs[ref].getSelection();
          this.logisticsCostPriceDetailTable.dataSource = this.logisticsCostPriceDetailTableDataSource.map(item => {
            if(currentSelection.indexOf(item.id) > -1){
              return {
                ...item,
                price: model.price,
                registerFee: model.registerFee
              }
            }else{
              return item;
            }
          })
          this.logisticsCostPriceDetailTableDataSource = this.logisticsCostPriceDetailTableDataSource.map(item => {
            if(currentSelection.indexOf(item.id) > -1){
              return {
                ...item,
                price: model.price,
                registerFee: model.registerFee
              }
            }else{
              return item;
            }
          })
        }
      },
    }
  }
</script>

<style scoped>
.tag{
  border: 1px solid #1890FF;
  padding: 2px 10px;
  border-radius: 6px;
  color: #1890FF;
  margin-bottom: 4px;
  display: inline-block;
}
/deep/.input-table .tbody .td input, /deep/.input-table .tbody .td input:disabled, /deep/.ant-select-disabled{
  color: rgba(0, 0, 0, 1);
}
.ant-spin-nested-loading{
  pointer-events: auto;
}
</style>